#!/bin/bash

# 演讲管理系统 - Odoo 后端部署脚本
# 使用方法: bash deploy.sh

echo "========================================="
echo "  演讲管理系统 - 后端部署脚本"
echo "========================================="
echo ""

# 配置变量
REMOTE_HOST="naturedao.tech"
REMOTE_USER="root"
REMOTE_PASSWORD="Winin112358Gy"
REMOTE_PATH="/root/odoo/extra-addons"
LOCAL_MODULE="explorers_backend/speech_management"
MODULE_NAME="speech_management"

echo "📦 准备部署..."
echo "远程服务器: $REMOTE_HOST"
echo "部署路径: $REMOTE_PATH"
echo "模块名称: $MODULE_NAME"
echo ""

# 检查本地模块是否存在
if [ ! -d "$LOCAL_MODULE" ]; then
    echo "❌ 错误: 找不到模块目录 $LOCAL_MODULE"
    exit 1
fi

echo "✅ 本地模块检查通过"
echo ""

# 步骤1: 压缩模块
echo "🗜️  步骤1: 压缩模块..."
tar -czf speech_management.tar.gz -C explorers_backend speech_management
if [ $? -eq 0 ]; then
    echo "✅ 压缩成功"
else
    echo "❌ 压缩失败"
    exit 1
fi
echo ""

# 步骤2: 上传到服务器
echo "📤 步骤2: 上传到服务器..."
sshpass -p "$REMOTE_PASSWORD" scp speech_management.tar.gz $REMOTE_USER@$REMOTE_HOST:/tmp/
if [ $? -eq 0 ]; then
    echo "✅ 上传成功"
else
    echo "❌ 上传失败，尝试手动上传"
    echo "手动命令: scp speech_management.tar.gz root@$REMOTE_HOST:/tmp/"
    exit 1
fi
echo ""

# 步骤3: 在服务器上解压和部署
echo "📦 步骤3: 在服务器上部署..."
sshpass -p "$REMOTE_PASSWORD" ssh $REMOTE_USER@$REMOTE_HOST << 'ENDSSH'
cd /tmp

# 备份旧模块（如果存在）
if [ -d "/root/odoo/extra-addons/speech_management" ]; then
    echo "📂 备份旧模块..."
    mv /root/odoo/extra-addons/speech_management /root/odoo/extra-addons/speech_management.bak.$(date +%Y%m%d_%H%M%S)
fi

# 解压新模块
echo "📦 解压新模块..."
tar -xzf speech_management.tar.gz -C /root/odoo/extra-addons/

# 设置权限
echo "🔐 设置权限..."
chown -R odoo:odoo /root/odoo/extra-addons/speech_management
chmod -R 755 /root/odoo/extra-addons/speech_management

# 重启Odoo
echo "🔄 重启Odoo服务..."
systemctl restart odoo

# 清理临时文件
rm -f /tmp/speech_management.tar.gz

echo "✅ 部署完成！"
ENDSSH

echo ""

# 步骤4: 清理本地临时文件
echo "🧹 步骤4: 清理临时文件..."
rm -f speech_management.tar.gz
echo "✅ 清理完成"
echo ""

# 完成
echo "========================================="
echo "  🎉 部署完成！"
echo "========================================="
echo ""
echo "📋 下一步操作:"
echo "1. 访问 https://$REMOTE_HOST"
echo "2. 进入 应用 -> 更新应用列表"
echo "3. 搜索 'Speech Management' 并安装"
echo "4. 测试 API: curl https://$REMOTE_HOST/api/v1/ping"
echo ""
echo "📖 详细文档请查看: docs/DEPLOYMENT.md"
echo ""

